package com.ChengXiZi.service.impl;

import com.ChengXiZi.constant.MessageConstant;
import com.ChengXiZi.dto.CommunityAddDTO;
import com.ChengXiZi.entity.Community;
import com.ChengXiZi.entity.User;
import com.ChengXiZi.entity.UserCommunity;
import com.ChengXiZi.exception.CommunityRepeatException;
import com.ChengXiZi.mapper.CommunityMapper;
import com.ChengXiZi.mapper.UserCommunityMapper;
import com.ChengXiZi.mapper.UserMapper;
import com.ChengXiZi.service.CommunityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CommunityServiceImpl implements CommunityService {

    @Autowired
    private CommunityMapper communityMapper;
    @Autowired
    private UserCommunityMapper userCommunityMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 创建社区
     * @param communityAddDTO
     * @return
     */
    @Override
    public void create(CommunityAddDTO communityAddDTO) {

        //创建community对象
        Community community = new Community();
        BeanUtils.copyProperties(communityAddDTO,community);

        //设置创建时间
        community.setCreateTime(LocalDateTime.now());

        //查询是否存在重名社区
        Community repeatCommunity = communityMapper.selectByName(community.getName());
        if(repeatCommunity != null) {
            throw new CommunityRepeatException(MessageConstant.COMMUNITY_REPEAT);
        }

        //新增社区
        communityMapper.insert(community);

        //封装版主的用户社区关系对象
        UserCommunity userCommunity = UserCommunity.builder()
                        .communityId(community.getId())
                        .userId(community.getOwner())
                        .role(2)
                        .status(1)
                        .joinTime(LocalDateTime.now())
                        .build();
        //新增用户社区关系表记录
        userCommunityMapper.insert(userCommunity);

        //将版主的身份设置为社区管理员
        User user = User.builder()
                        .id(community.getOwner())
                        .identity(1)
                        .build();
        userMapper.update(user);
    }
}
